import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { promises as fsPromises } from "fs";
import Papa from "papaparse";

// 生成考试的唯一标识
function generateExamId(grade: string, examName: string, examDate: string): string {
  return `${grade}_${examName}_${examDate}`;
}

// 获取访问量数据文件
async function getMetricsFile() {
  const workingDir = process.cwd();
  const metricsDir = path.join(workingDir, "data", "metrics");
  const metricsFile = path.join(metricsDir, "visits.json");
  
  // 确保目录存在
  try {
    await fsPromises.access(metricsDir);
  } catch (error) {
    // 目录不存在，创建它
    await fsPromises.mkdir(metricsDir, { recursive: true });
  }
  
  // 确保文件存在
  try {
    await fsPromises.access(metricsFile);
  } catch (error) {
    // 文件不存在，创建初始数据
    const initialData = {
      homepageVisits: 0,
      exams: {}
    };
    await fsPromises.writeFile(metricsFile, JSON.stringify(initialData, null, 2));
  }
  
  return metricsFile;
}

// 读取访问量数据
async function readMetricsData() {
  try {
    const metricsFile = await getMetricsFile();
    const data = await fsPromises.readFile(metricsFile, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    console.error("读取访问量数据出错:", error);
    return { homepageVisits: 0, exams: {} };
  }
}

// 写入访问量数据
async function writeMetricsData(data: any) {
  try {
    const metricsFile = await getMetricsFile();
    await fsPromises.writeFile(metricsFile, JSON.stringify(data, null, 2));
  } catch (error) {
    console.error("写入访问量数据出错:", error);
  }
}

// 通过考试名称查询完整考试信息
async function findExamInfo(examName: string): Promise<{ grade: string; examDate: string } | null> {
  try {
    const workingDir = process.cwd();
    const csvDir = path.join(workingDir, "data", "csv");
    
    // 确保目录存在
    try {
      await fsPromises.access(csvDir);
    } catch (error) {
      return null;
    }
    
    // 获取所有的CSV文件
    const files = await fsPromises.readdir(csvDir);
    const csvFiles = files.filter(file => file.endsWith(".csv"));
    
    if (csvFiles.length === 0) {
      return null;
    }
    
    // 读取并解析所有CSV文件
    for (const file of csvFiles) {
      const filePath = path.join(csvDir, file);
      const fileContent = await fsPromises.readFile(filePath, "utf-8");
      
      // 使用PapaParse解析CSV
      const { data, errors } = Papa.parse(fileContent, {
        header: true,
        skipEmptyLines: true,
        transformHeader: (header) => header.trim(),
        transform: (value) => {
          // 保留原始格式，确保"+"不被转换
          return value.trim();
        }
      });
      
      if (errors.length > 0) {
        console.error(`解析文件 ${file} 时出错:`, errors);
        continue;
      }
      
      // 查找匹配的考试
      const matchedExam = data.find((exam: any) => {
        // 考试名称可能包含在课程名称中
        return exam.课程名称 && exam.课程名称.includes(examName);
      });
      
      if (matchedExam) {
        return {
          grade: (matchedExam as any).年级,
          examDate: (matchedExam as any).考试日期.replace(/-/g, '/')
        };
      }
    }
    
    return null;
  } catch (error) {
    console.error("查询考试信息失败:", error);
    return null;
  }
}

// GET请求处理 - 获取访问量数据
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const examId = searchParams.get("examId");
    const grade = searchParams.get("grade");
    const examName = searchParams.get("examName");
    const examDate = searchParams.get("examDate");
    
    // 添加调试日志
    console.log("GET 请求参数:", { examId, grade, examName, examDate });
    
    const metricsData = await readMetricsData();
    console.log("当前访问记录:", metricsData);
    
    if (examId) {
      // 如果直接提供了examId参数
      if (examId.includes("_")) {
        // 返回特定考试的访问量
        const examVisits = metricsData.exams[examId] || 0;
        console.log(`通过examId=${examId}查询结果:`, examVisits);
        return NextResponse.json({ visits: examVisits });
      } else {
        // 如果只提供了考试名称，则尝试查找匹配的考试访问量
        // 先直接在已有记录中模糊查找
        const matchingKeys = Object.keys(metricsData.exams).filter(key => 
          key.includes(examId)
        );
        
        if (matchingKeys.length > 0) {
          // 找到模糊匹配的记录
          const totalVisits = matchingKeys.reduce((sum, key) => sum + metricsData.exams[key], 0);
          console.log(`通过模糊匹配examId=${examId}找到记录:`, matchingKeys, totalVisits);
          return NextResponse.json({ visits: totalVisits });
        }
        
        // 未找到时尝试查找考试信息
        const examInfo = await findExamInfo(examId);
        
        if (examInfo) {
          const fullExamId = generateExamId(examInfo.grade, examId, examInfo.examDate);
          const examVisits = metricsData.exams[fullExamId] || 0;
          console.log(`通过考试信息查找后的examId=${fullExamId}结果:`, examVisits);
          return NextResponse.json({ visits: examVisits });
        } else {
          // 如果找不到匹配的考试，则返回0访问量
          console.log(`未找到匹配的考试信息:`, examId);
          return NextResponse.json({ visits: 0 });
        }
      }
    } else if (grade && examName && examDate) {
      // 当提供了完整的考试信息参数时
      const fullExamId = generateExamId(grade, examName, examDate);
      console.log(`构建的完整examId:`, fullExamId);
      
      // 先尝试精确匹配
      let examVisits = metricsData.exams[fullExamId] || 0;
      
      // 如果没有找到，尝试模糊匹配
      if (examVisits === 0) {
        const matchingKeys = Object.keys(metricsData.exams).filter(key => 
          key.includes(examName)
        );
        
        if (matchingKeys.length > 0) {
          examVisits = matchingKeys.reduce((sum, key) => sum + metricsData.exams[key], 0);
          console.log(`通过模糊匹配找到记录:`, matchingKeys, examVisits);
        }
      }
      
      console.log(`通过grade=${grade}, examName=${examName}, examDate=${examDate}查询结果:`, examVisits);
      return NextResponse.json({ visits: examVisits });
    } else if (examName) {
      // 仅提供考试名称的情况，允许模糊匹配
      // 先在已有记录中查找包含该考试名称的记录
      const matchingKeys = Object.keys(metricsData.exams).filter(key => 
        key.includes(examName)
      );
      
      if (matchingKeys.length > 0) {
        const totalVisits = matchingKeys.reduce((sum, key) => sum + metricsData.exams[key], 0);
        console.log(`通过模糊匹配examName=${examName}找到记录:`, matchingKeys, totalVisits);
        return NextResponse.json({ visits: totalVisits });
      }
      
      // 未找到时尝试查找考试信息
      const examInfo = await findExamInfo(examName);
        
      if (examInfo) {
        const fullExamId = generateExamId(examInfo.grade, examName, examInfo.examDate);
        const examVisits = metricsData.exams[fullExamId] || 0;
        console.log(`通过考试信息查找后的examId=${fullExamId}结果:`, examVisits);
        return NextResponse.json({ visits: examVisits });
      } else {
        // 如果找不到匹配的考试，则返回0访问量
        console.log(`未找到匹配的考试信息:`, examName);
        return NextResponse.json({ visits: 0 });
      }
    } else {
      // 返回首页访问量和所有考试访问量
      return NextResponse.json(metricsData);
    }
  } catch (error) {
    console.error("获取访问量数据出错:", error);
    return NextResponse.json({ error: "获取访问量数据时出错" }, { status: 500 });
  }
}

// POST请求处理 - 增加访问量
export async function POST(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const type = searchParams.get("type");
    
    const metricsData = await readMetricsData();
    console.log("POST请求类型:", type);
    
    if (type === "homepage") {
      // 增加首页访问量
      metricsData.homepageVisits = (metricsData.homepageVisits || 0) + 1;
      console.log("首页访问量更新为:", metricsData.homepageVisits);
    } else if (type === "exam") {
      // 从请求体获取考试信息
      const body = await request.json();
      let { grade, examName, examDate } = body;
      
      console.log("收到考试访问请求:", body);
      
      if (!examName) {
        console.log("缺少必要的考试信息");
        return NextResponse.json({ error: "缺少必要的考试信息" }, { status: 400 });
      }
      
      // 如果没有提供年级和日期，尝试从考试名称自动补全
      if (!grade || !examDate) {
        const examInfo = await findExamInfo(examName);
        console.log("通过名称查找考试信息:", examInfo);
        
        if (examInfo) {
          grade = grade || examInfo.grade;
          examDate = examDate || examInfo.examDate;
        } else {
          // 如果无法确定年级和日期，使用默认值确保仍能生成ID
          grade = grade || "未知";
          examDate = examDate || "未知";
        }
      }
      
      // 处理年级格式：将"2022级"这种格式处理为"2022"
      if (grade && grade.includes("级")) {
        grade = grade.replace("级", "");
      }
      
      const examId = generateExamId(grade, examName, examDate);
      console.log("生成的examId:", examId);
      
      metricsData.exams[examId] = (metricsData.exams[examId] || 0) + 1;
      console.log(`考试 ${examId} 访问量更新为:`, metricsData.exams[examId]);
    } else {
      console.log("无效的访问类型:", type);
      return NextResponse.json({ error: "无效的访问类型" }, { status: 400 });
    }
    
    await writeMetricsData(metricsData);
    console.log("访问数据已写入");
    
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("增加访问量出错:", error);
    return NextResponse.json({ error: "增加访问量时出错" }, { status: 500 });
  }
} 